package com.xingfly.service;

import com.xingfly.model.Comment;
import com.xingfly.model.User;
import com.xingfly.repository.CommentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 评论服务
 * Created by SuperS on 2016/12/8.
 */
@Service
public class CommentService {

    public static final int COUNT = 10;
    @Autowired
    private CommentRepository commentRepository;

    @Autowired
    private AccountService accountService;

    /**
     * 创建评论
     */
    public Comment create(Comment comment) {
        return commentRepository.save(comment);
    }

    /**
     * 根据ID查找评论
     */
    public Comment find(Long id) {
        return commentRepository.findOne(id);
    }

    /**
     * 根据类型和ID查找评论 并且使用自定义分页
     *
     * @param objectType 对象类型
     * @param objectId   对象ID
     * @param offset     sql语句limit第一位
     * @param count      sql语句limit第二位
     */
    public List<Comment> getComments(int objectType, Long objectId, int offset, int count) {
        return commentRepository.findByCommentObjectTypeAndCommentObjectId(objectType, objectId, new PageRequest(offset, count));
    }

    /**
     * 根据类型和ID查找评论 并且使用默认分页
     *
     * @param objectType 对象类型
     * @param objectId   对象ID
     */
    public List<Comment> getComments(int objectType, Long objectId) {
        return commentRepository.findByCommentObjectTypeAndCommentObjectId(objectType, objectId, new PageRequest(0, COUNT));
    }

    /**
     * 根据commentID查找 Author
     *
     * @param id 评论ID
     */
    public User findAuthorByCommentId(Long id) {
        return commentRepository.findAuthorByCommentId(id);
    }

    /**
     * 获取评论数量
     *
     * @param objectType 对象类型
     * @param objectId   对象ID
     */
    public long getCommentsCount(int objectType, Long objectId) {
        return commentRepository.getCommentsCount(objectType, objectId);
    }


}
